//
//  HRRegisterPhotoViewController.m
//  SpeedDating
//
//  Created by ISU1 on 16/12/16.
//  Copyright © 2016年 isu. All rights reserved.
//

#import "RegisterPhotoViewController.h"
//#import "HRSpeedDatingViewController.h"
//#import "HRMessageViewController.h"
//#import "HRPersonalViewController.h"
//#import "HRTopicViewController.h"
#import "YSHYClipViewController.h"
#import "MZCTabBarController.h"
#import "GGActionSheet.h"
@interface RegisterPhotoViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,GGActionSheetDelegate>


@property (nonatomic, strong) UIButton *photoButton;



@property (nonatomic, strong) UIButton *enterButton;

@property (nonatomic, strong) UIImage *selectImage;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) GGActionSheet *actionSheetTitle;



@end

@implementation RegisterPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setNavgationBarHidden];
    self.view.backgroundColor = [UIColor whiteColor];
    [self configureUI];
 

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}

- (void)configureUI {
    UIView *viewBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 64)];
    viewBg.backgroundColor = Colorbackground;
    

    
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, KScreenWidth, 34)];
    titleLab.text = @"上传形象照片";
    titleLab.font = Font(18);
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.backgroundColor = Colorbackground;
    titleLab.textColor = [UIColor blackColor];
    
    [viewBg addSubview:titleLab];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(22, 19.5, 44, 44)];
    btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//设置文字位置，现设为居左，默认的是居中=
    [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 5.5, 0, 0);
    [btn addTarget:self action:@selector(backActionbtn) forControlEvents:UIControlEventTouchUpInside];
    [viewBg addSubview:btn];
    [self.view addSubview:viewBg];
    
    if ([_perfectType isEqualToString:@"1"]) {
        btn.hidden = YES;
    }else{
        btn.hidden = NO;
    }
    
    UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 64+(52*SCREEN_WIDTH_RATIO47), KScreenWidth, 50*SCREEN_WIDTH_RATIO47)];
    noteLabel.textColor = [UIColor lightGrayColor];
    noteLabel.numberOfLines = 0;
    noteLabel.textAlignment = NSTextAlignmentCenter;
    noteLabel.text = @"请上传一张您的真实露脸照";

    [self.view addSubview:noteLabel];
    _photoButton = [[UIButton alloc] init];
    _photoButton.layer.cornerRadius = (180*SCREEN_WIDTH_RATIO47)/2;
    _photoButton.layer.masksToBounds = YES;
    
    if ([_sexNum isEqualToString:@"0"]) {
        [_photoButton setBackgroundImage:[UIImage imageNamed:@"head_partrait_girl"] forState:UIControlStateNormal];
    }else{
        [_photoButton setBackgroundImage:[UIImage imageNamed:@"head_partrait_boy_w"] forState:UIControlStateNormal];

    }
    [_photoButton addTarget:self action:@selector(clickPhotoButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_photoButton];
    [_photoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.width.height.mas_equalTo(180*SCREEN_WIDTH_RATIO47);
        make.top.equalTo(noteLabel.mas_bottom).offset(29*SCREEN_WIDTH_RATIO47);
    }];
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.text = @"点击上传照片";
    _titleLabel.textColor = [UIColor lightGrayColor];
    [self.view addSubview:_titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_photoButton.mas_bottom).offset(15);
    }];
    _enterButton = [[UIButton alloc] init];
    [_enterButton setTitle:@"点击进入主页" forState:UIControlStateNormal];
    [_enterButton setTitleColor:ColorI(0xffeb8e) forState:UIControlStateNormal];
    _enterButton.hidden = YES;
    [_enterButton addTarget:self action:@selector(clickEnterButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_enterButton];
    [_enterButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_photoButton.mas_bottom).offset(15);
    }];
    
}
- (void)backActionbtn{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)clickPhotoButton{
    [self.actionSheetTitle showGGActionSheet];
    
}
-(GGActionSheet *)actionSheetTitle{
    if (!_actionSheetTitle) {
        _actionSheetTitle = [GGActionSheet ActionSheetWithTitleArray:@[@"相册",@"相机"] andTitleColorArray:@[[UIColor blackColor]] delegate:self];
        //取消按钮颜色设置
        _actionSheetTitle.cancelDefaultColor = [UIColor blackColor];
        //如果设置了选项颜色 当颜色数组和标题数组数量对不上时 多余标题使用选项默认颜色
        //如果设置了选项颜色 当颜色数组传空时，所有选项默认使用选项颜色
        //如果没设置选项颜色 数量对不上以及颜色数组为空时都使用默认黑色
        _actionSheetTitle.optionDefaultColor = [UIColor blackColor];
    }
    return _actionSheetTitle;
}
//弹框点击
-(void)GGActionSheetClickWithActionSheet:(GGActionSheet *)actionSheet Index:(int)index{
    
    if (index == 0) {
        
        [self addPhoto];

    }else if (index == 1){
        [self takePhoto];

        
    }
    
}




- (void)clickSkipButton {
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_isLogin object:@(NO)];
}

- (void)addPhoto {

    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    [picker.navigationBar setBackgroundImage:[UIImage imageNamed:@"NagavitionBarImg"] forBarMetrics:UIBarMetricsDefault];

    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
    
}

- (void)takePhoto {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        
   
        
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }else
    {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}


-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"]){
        
        //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出
        UIImage* oldImage = [info objectForKey:UIImagePickerControllerEditedImage];
        
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *scaleImage = [self scaleImage:oldImage toScale:0.3];
        
        UIImageOrientation imageOrientation = scaleImage.imageOrientation;
        
        UIImage * image;
        if(imageOrientation!=UIImageOrientationUp)
        {
            // 原始图片可以根据照相时的角度来显示，但UIImage无法判定，于是出现获取的图片会向左转９０度的现象。
            // 以下为调整图片角度的部分
            UIGraphicsBeginImageContext(scaleImage.size);
            [scaleImage drawInRect:CGRectMake(0, 0, scaleImage.size.width, scaleImage.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            // 调整图片角度完毕
        }else{
            image = scaleImage;
        }
        NSData *data;
        
        if (UIImagePNGRepresentation(image) == nil){
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else{
            data = UIImagePNGRepresentation(image);
        }
        
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.jpg
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:^{
            
            UIImage * img = [UIImage imageWithData:data];
            [_photoButton setBackgroundImage:img forState:UIControlStateNormal];

            _selectImage = img;
            
            _enterButton.hidden = NO;
            _titleLabel.hidden = YES;
            
        }];
        
        
        
    }
    
}


#pragma mark- 缩放图片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
/**
 *  用户点击取消按钮时调用
 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}



- (void)clickEnterButton {
    [SVProgressHUD show];
    self.view.userInteractionEnabled = NO;
    [HQHttpManager uploadimgsWithImage:_selectImage belong:@"photo" toAlbum:@(0) albumId:nil successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            NSString *imageUrl = resultDic[@"res"];
            [HQHttpManager updateUserWithUid:[HQHttpManager getUserId] mobile:nil photo:imageUrl motto:nil sex:nil nickName:nil birthday:nil animal:nil height:nil weight:nil affection:nil email:nil job:nil hometown:nil activeSite:nil skill:nil wantSkill:nil zfb:nil zfbName:nil cardImg:nil video:nil privacy:nil isShield:nil successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                if (isSuccess) {
                    
                    [SVProgressHUD dismiss];
                    self.view.userInteractionEnabled = YES;
               
                    [HQHttpManager userInfo2WithUid:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                        
                        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"infoStatus"];
                        
                        [defaults setValue:resultDic[@"infoStatus"] forKey:@"infoStatus"];
                        
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        
                        [self clickSkipButton];

                    }];
                } else {
                    [SVProgressHUD dismiss];
                    self.view.userInteractionEnabled = YES;
                }
            }];
        } else {
            [SVProgressHUD dismiss];
            self.view.userInteractionEnabled = YES;
        }
    }];
}



@end
